package dytmp

import (
	"context"
	"dy/internal/configs/config"
	"fmt"
	"os"

	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"go.uber.org/zap"
)

var (
	MinIOClient     *minio.Client
	MinioSsl        = false
	MinioEndpoint   = config.Conf.MinIO.MinioEndpoint
	AccessKeyId     = config.Conf.MinIO.AccessKeyId
	SecretAccessKey = config.Conf.MinIO.SecretAccessKey
	Location        = config.Conf.MinIO.Location
	BucketName      = config.Conf.MinIO.BucketName
)

func init() {
	bucketName := BucketName
	ctx := context.Background()

	// 初使化 minio client对象。
	fmt.Println("====>", os.Getenv("ENDPOINT"))
	minioClient, err := minio.New(
		MinioEndpoint,
		&minio.Options{
			Creds: credentials.NewStaticV4(
				AccessKeyId,
				SecretAccessKey,
				""),
			Secure: MinioSsl,
		})

	if err != nil {
		panic(err)
	}

	err = minioClient.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{Region: Location})
	if err != nil {
		// 检查存储桶是否已经存在。
		exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
		if errBucketExists == nil && exists {
			fmt.Println("We already own ", zap.String("bucketName", bucketName))
		} else {
			fmt.Println("MinIO 创建桶失败", zap.Error(err))
			panic(err)
		}
	} else {
		fmt.Println("Successfully created", zap.String("bucketName", bucketName))
	}

	MinIOClient = minioClient
}
